<?php
/**
 * +--------------------------------------------------------+
 * @Created by Phpstorm.
 * @Category DingDing.php
 * @Depiction
 * @Author hwy <429208948@qq.com>
 * @Date 2022/5/23  10:32
 * +--------------------------------------------------------+
 */

namespace App\Util;


use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

class DingDing
{
    private $robot_url;

    public function textMsgSend($msg, $mobile = [], $type = 1)
    {
        if ($type == 1) {
            $this->robot_url = env('DING_TALK', '');
        } else if ($type == 2) {
            $this->robot_url = env('YBS_DING_TALK', '');
        } else if ($type == 3) {
            $this->robot_url = 'https://oapi.dingtalk.com/robot/send?access_token=044940011f61dcda87f0f1991d8424ff6fd2bccaa2d1c7b6e912d76d066a1083';
        } else {
            $this->robot_url = env('YBS_DING_TALK', '');
        }
        $msgJson = json_encode([
            'msgtype' => 'text',
            'text'    => [
                "content" => $msg,
            ],
            'at'      => [
                'atMobiles' => $mobile,
                'isAtAll'   => false,
            ],
        ]);

        $result = $this->sendRequest($msgJson, $this->robot_url);
        return $result;
    }

    public function sendRequest($json, $robot_url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $robot_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json;charset=utf-8']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 不用开启curl证书验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $response = curl_exec($ch);

        //增加curl日志
        $log_curl['url']        = $this->robot_url;
        $log_curl['input']      = is_string($json) ? $json : json_encode($json);
        $log_curl['created_at'] = Carbon::now()->toDateTimeString();
        if ($response === false) {
            // echo "cURL Error: " . curl_error($ch);
            $log_curl['result'] = curl_error($ch);
            $log_curl['status'] = 2;
        } else {
            $responses = iconv("gb2312", "utf-8//IGNORE", $response);
            $result    = is_string($responses) ? $responses : json_encode($responses);
            if (strlen($result) > 2000) {
                $result = 'too long';
            }
            $log_curl['result'] = $result;
            $log_curl['status'] = 1;
        }

        $curl_log_cache_name    = 'log_curl_cache_name';
        $log_curl['created_at'] = Carbon::now()->toDateTimeString();
        Redis::rpush($curl_log_cache_name, json_encode($log_curl));

        curl_close($ch);

        return $response;
    }
}
